<template>
  <view class="taskStep">
    <view class="header">
      <!-- <uni-nav-bar left-icon="back" :title="title || '--'" statusBar="true" :fixed="false"
				backgroundColor="rgba(0, 0, 0, 0)" @clickLeft="handleBack"></uni-nav-bar> -->
      <view class="nav" :style="{ background: showBg ? '#fff' : '' }">
        <global-nav-bar
          type="black"
          left-icon="back"
          color="#333"
          :title="title"
          :fixed="false"
          backgroundColor="rgba(0, 0, 0, 0)"
        ></global-nav-bar>
      </view>
      <view>
        <image
          class="bg"
          src="https://592800-erised-fresh.oss-cn-shenzhen.aliyuncs.com/upload/20221012/c1a6e9996af7e11408d283b788eb2b33.png"
          mode=""
          v-if="!showBg"
        ></image>
      </view>
      <!-- 头部部分header -->
      <view class="header_item">
        <view class="header_top" @click="toInfos()">
          <view class="header_top_left">{{
            cutLenght(
              elevatorDetail.buildingName + elevatorDetail.elevatorAddress
            )
          }}</view>
          <uni-icons color="#999" v-if="elevatorDetail.id" size="18" type="arrowright" />
        </view>
        <view class="header_bottom" v-if="elevatorDetail.id">
          <view class="header_bottom_left">
            {{ elevatorDetail.brandName || "--" }}|
            {{ elevatorDetail.privateNum || "--" }}
          </view>
          <view class="header_bottom_right" @click="toInfos()" >
            <image src="/static/images/tips.png" mode="" />
            <uni-icons color="#666" size="18" type="arrowright" />
          </view>
        </view>
      </view>
      
      <image
        src="https://592800-erised-fresh.oss-cn-shenzhen.aliyuncs.com/upload/20221012/c1a6e9996af7e11408d283b788eb2b33.png"
        mode=""
        class="bg"
      ></image>
      <view class="addressBox" v-if="elevatorDetail.id">
        <view class="addressBox_left">
          <view class="top">
            <view class="name">
              <image src="@/static/images/index/buildIcon.svg" mode=""></image>
              <view style="margin-left: 10rpx">{{
                elevatorDetail.buildingName
              }}</view>
            </view>
          </view>
          <view
            class="buildAddress"
            style="display: flex; align-items: center"
            @click.stop="petName(elevatorDetail)"
            v-if="
              elevatorDetail.relationAlias &&
              elevatorDetail.relationAlias.length
            "
          >
            <view class="buildings"
              >项目别名:{{
                elevatorDetail.relationAlias.map((item) => item.alias).join(",")
              }}</view
            >
            <view>
              <uni-icons
                :type="popupShow ? 'arrowup' : 'arrowdown'"
                size="14"
                color="#999;"
              ></uni-icons>
            </view>
          </view>
          <view class="buildAddress" @click.stop="toProjectDetail">{{
            elevatorDetail.buildingAddress
          }}</view>
        </view>
        <view class="addressBox_right">
          <view class="gpsAndCall">
            <view
              class="gpsAndCall_item"
              @click.stop="handleCall"
              v-if="
                elevatorDetail.estateUserList &&
                elevatorDetail.estateUserList.length
              "
            >
              <image src="@/static/images/phone3.png" mode=""></image>
              <view>物业</view>
            </view>
            <view class="gpsAndCall_item guide" @click.stop="toMap">
              <image src="@/static/images/locations.png" mode=""></image>
              <view>导航</view>
            </view>
            <view
              class="line"
              v-if="
                elevatorDetail.estateUserList &&
                elevatorDetail.estateUserList.length
              "
            ></view>
          </view>
        </view>
      </view>
    </view>
    <view>
   
      <!-- <view class="addressBox" @click="toProjectDetail">
        <view class="top">
          <view class="name">
            <image src="@/static/images/index/buildIcon.svg" mode=""></image>
            <view style="margin-left: 10rpx"
              >{{ elevatorDetail.buildingName }}
            </view>
          </view>
        </view>
        <view class="buildAddress">{{ elevatorDetail.buildingAddress }}</view>
      </view> -->
      <view class="content">
        <view class="content_chi">
          <view class="t_name">
            {{ title || "--" }}
          </view>
          <view class="t_Times" v-if="planTimes">
            <image
              src="/static/images/maintain/funnel.png"
              mode=""
            ></image>
            <text>任务耗时：{{ planTimes + "分钟" }}</text>
          </view>
          <view class="" v-if="dataArray.length > 0">
            <stepInfo v-if="repairState !== 2" :dataList="dataArray" :typeStatus="typeStatus" @seeClick="seeClick" />
            <rescueStepInfo v-else :dataList="dataArray" :status="status" @seeClick="seeClick" />
          </view>
          <view
            v-else
            style="
              height: 200rpx;
              line-height: 200rpx;
              color: #cccccc;
              text-align: center;
            "
          >
            暂无数据进度
          </view>
        </view>
      </view>
    </view>
    <!-- <uni-popup ref="previewwGuide" type="center">
				<view class="" style=" background-color: #FFFFFF; width: 710rpx; height: 800rpx;padding: 20rpx;" @click="this.$refs.previewwGuide.close()">
					<image style="width: 710rpx; height: 800rpx;" src="@/static/SIDAlogo@2x.png" mode=""></image>
				</view>
		</uni-popup> -->
    <property-phone ref="property" @bindClose="closePhone" :list="elevatorDetail.estateUserList"></property-phone>
    <!-- 项目别名弹窗 -->
    <aliasPopup
      :showAlias="popupShow"
      :aliasArr="aliasArr"
      @closedMask="closedMask"
    ></aliasPopup>
    <previewMedia ref="previewMedia"></previewMedia>
  </view>
</template>

<script>
import uniNavBar from '@/components/uni-nav-bar/uni-nav-bar.vue';
import stepInfo from './compontens/stepInfo.vue';
import rescueStepInfo from './compontens/rescueStepInfo.vue';
import { getSelectWorkTracks } from '@/apis/taskStepPage.js';
import GlobalNavBar from '@/components/uni-nav-bar/global-nav-bar';
import { elevtorDetail } from '@/apis/elevator.js';
import aliasPopup from '@/components/card-dial/aliasPopup.vue';
import PropertyPhone from '@/components/propertyPhone/index.vue';
import { getPathInfo } from '@/utils/watermarkTool.js';
export default {
	components: {
		uniNavBar,
		stepInfo,
		rescueStepInfo,
		GlobalNavBar,
		aliasPopup,
		PropertyPhone
	},
	data() {
		return {
			dataArray: [],
			showImg: false, // 查看图片状态
			elevatorDetail: {},
			taskTitle: '',
			title: '',
			templateList: [],
			typeList: ['', '半月', '季度', '半年', '年度', '自定义'],
			repairState: 0, // 维修页面状态

			planTimes: null, // 任务耗时
			strText: '',
			showBg: false,
			elevatorId: '',
			isFull: false,
			planId: '',
			popupShow: false,
			aliasArr: [],
			typeStatus:'',// 工单类型
			status:'', // 工单状态
		};
	},

	props: {
		// title:{
		// 	type:String,
		// 	default:"任务追踪"
		// },
		// elevatorDetail:{
		// 	type:Object,
		// 	default:{}
		// }
	},
	onPageScroll(e) {
		// console.log(e.scrollTop, '滚动')
		if (e.scrollTop > 20) {
			this.navBarTitle = this.elevatorDetail.elevatorAddress;
			this.scrollTop = e.scrollTop;
			this.showBg = true;
		} else {
			this.showBg = false;
		}
	},
	computed: {},
	mounted() {},
	onLoad(opt) {
		if (Object.keys(opt).length <= 0) {
			return;
		}
		// this.elevatorDetail = JSON.parse(opt.obj);
		this.repairState = Number(opt.state) || 0;
		this.elevatorId = opt.elevatorId;
		this.status = opt.status || '';
		this.planId = opt.planId;
		this.elevtorDetail();
		let planCheckType = this.elevatorDetail.planCheckType;
		if (this.repairState === 2) {
			this.title = '救援任务追踪';
		} else if (this.repairState === 1) {
			this.title = '维修任务追踪';
		} else if (this.repairState === 3) {
			this.title = '事务任务追踪';
		} else if (this.repairState === 4) {
			this.title = '质检任务追踪';
		} else if (this.repairState === 9) {
			this.title = '维保整改工单跟踪';
		} else {
			if (planCheckType) {
				this.title = this.typeList[planCheckType] + '保养';
			}
			if (planCheckType === 9) {
				this.title = '专项保养';
			}
		}
		this.initGetStep(this.planId);
	},
	methods: {
  
		// 拨打电话
		handleCall() {
			this.$nextTick(() => {
				this.$refs.property.$refs.propertyPhone.open();
			});
		},
		closePhone() {
			this.$nextTick(() => {
				this.$refs.property.$refs.propertyPhone.close();
			});
		},
		// 地图导航
		getAliasStr(str) {
			if (!str) {
				return '';
			}
			if (str.length > 20) {
				return '(项目别名：' + str.slice(0, 20) + '...)';
			} else {
				return '(项目别名：' + str + ')';
			}
		},
		toMap() {
			// console.log(this.elevatorDetail)
			let alias = this.elevatorDetail.relationAlias;
			let aliasName = alias.length
				? alias
					.map((item) => {
						return item.alias;
					})
					.join(',')
				: '';
			uni.openLocation({
				latitude: Number(this.elevatorDetail.latitude),
				longitude: Number(this.elevatorDetail.longitude),
				name: this.elevatorDetail.buildingName + this.getAliasStr(aliasName),
				address: this.elevatorDetail.buildingAddress,
				fail: (err) => {
					console.log(err);
				},
			});
		},
		// 项目别名弹窗
		petName(obj) {
			this.popupShow = true;

			this.aliasArr = (obj.relationAlias || []).map((item) => item.alias);
		},
		closedMask(e) {
			this.popupShow = false;
		},
		// 获取电梯详情
		elevtorDetail() {
			if (!this.elevatorId || this.elevatorId == 0) {
				this.elevatorDetail = {
					buildingName:'',
					elevatorAddress:'电梯未知'
				};
				uni.hideLoading();
				return;
			}
			elevtorDetail({ elevatorId: this.elevatorId }).then((res) => {
				if (res) {
					uni.hideLoading();

					this.elevatorDetail = res.data;
					this.elevatorDetail.planId = this.planId;
					this.isFull = res.data.isFull;
				}
			});
		},

		// 跳转项目详情
		toProjectDetail() {
			uni.navigateTo({
				url:
          '/pageModules/projectInfo/detail?id=' +
          this.elevatorDetail.buildingId,
			});
		},
		// 跳转电梯详情
		toEleDetail() {
			if (!this.elevatorDetail.id) {
				return;
			}
			uni.navigateTo({
				url: `/subpages/elevator/projectInfo/eleDetail?id=${this.elevatorDetail.id}`,
			});
		},
		initGetStep(planId) {
			getSelectWorkTracks({
				planId,
			}).then((res) => {
				if (res.code === 200) {
					let workArr = res.data.workLogs || [];
					this.typeStatus = res.data.typeStatus;
					console.log(this.typeStatus);
					if (workArr.length > 0) {
						workArr = workArr.map((item) => {
							return {
								...item,
								modelId: '',
								aiResult:'',
								extPlus: JSON.parse(item.ext || '{}'),
							};
						});
						this.planTimes =
              res.data.takeUpTime != 'null' ? Number(res.data.takeUpTime) : 0;

						this.dataArray = JSON.parse(JSON.stringify(workArr));
						this.dataArray.reverse();
						// let majorState = this.dataArray.some(item=> item.planStatus === 6)
						let obj = {
							createTime: '',
							executor: '已完成',
							typeName: '',
							aiResult:'',
							modelId:''
						};
						let a = workArr.length - 1;
						let planStatusArr = [
							{
								createTime: '',
								executor: '待开始',
								typeName: '',
								active: true,
								status: 1,
							},
							{
								createTime: '',
								executor: '待开始',
								typeName: '',
								active: true,
								status: 2,
							},
							{
								createTime: '',
								executor: '已完成',
								typeName: '',
								active: true,
								status: 3,
							},
							{
								createTime: '',
								executor: '已完成',
								typeName: ' ',
								active: false,
								status: 4,
							},
							// 救援5是已完成
							{
								createTime: '',
								executor: '已完成',
								typeName: ' ',
								active: false,
								status: 5,
							},
							{
								createTime: '',
								executor: '已关闭',
								typeName: ' ',
								active: false,
								status: 7,
							},
						];
						for (let i = 0; i < planStatusArr.length; i++) {
							if (planStatusArr[i].status === workArr[a].planStatus) {
								obj.executor = planStatusArr[i].executor;
								obj.typeName = planStatusArr[i].typeName;
								obj.active = planStatusArr[i].active;
							}
						}
          
						this.dataArray.unshift(obj);
						console.log(this.dataArray,111);

						this.getAiResults();
					}
				}
			});
		},
		getHeadInfo(url) {
			if (url.indexOf('aliyuncs.com') == -1) {
				return getPathInfo(url);
			}
			return new Promise((resolve) => {
				// #ifdef H5
				this.http.head(url).then(header => {
					const newHeader = {};
					Object.keys(header).forEach(key => {
						// 转码，兼容中文字符 
						newHeader[key] = decodeURIComponent(header[key]);
					});
					resolve(newHeader);
				});
				// #endif

				// #ifndef H5
				uni.request({
					method: 'HEAD',
					url,
					success(res) {
						let header = res.header || {};
						Object.keys(header).forEach(key => {
							// 转码，兼容中文字符
							header[key] = decodeURIComponent(header[key]);
						});
						resolve(header);
					}, fail() {
						resolve({});
					}
				});
				// #endif
			});
		},
      		// 异步获取ai结果
		async getAiResults() {
			for (let i = 0; i < this.dataArray.length; i++) {
				if (this.dataArray[i].extPlus && this.dataArray[i].extPlus.image) {
					const imgHead = await this.getHeadInfo(this.dataArray[i].extPlus.image);
					
					if (imgHead && imgHead['x-oss-meta-model-id'] && imgHead['x-oss-meta-business-result'] != undefined) {
						this.dataArray[i].modelId = imgHead['x-oss-meta-model-id'];
						this.dataArray[i].aiResult = imgHead['x-oss-meta-business-result'];
					}
				}
			}
			console.log('getAiResults', this.dataArray);
			this.$forceUpdate();
		},
		handleBack() {
			uni.navigateBack({
				delta: 1,
			});
		},
		cutLenght(val) {
			if (val.length > 12) {
				return val.substring(0, 12) + '...';
			}
			return val;
		},
		// 查看图片
		seeClick(val) {
			this.$previewMedia({
				current: 0, 
				sources: [val],  
			});
			// this.$refs.previewwGuide.open()
		},
		showPath() {
			console.log('showPath', this.elevatorDetail);
			if (!this.elevatorDetail.latitude) {
				return;
			}
			uni.openLocation({
				latitude: parseFloat(this.elevatorDetail.latitude),
				longitude: parseFloat(this.elevatorDetail.longitude),
				name: this.elevatorDetail.buildingName,
				address: this.elevatorDetail.buildingAddress,
				scale: 18,
				complete: (e) => {
					console.log(e);
				},
				success(e) {},
			});
		},
		// 电梯详情
		toInfos() {
			if (!this.elevatorDetail.id) return; // 救援工单 没有电梯elevatorId情况
			console.log('救援工单 没有电梯elevatorId情况');
			let urls = '/subpages/elevator/projectInfo/elevatorInfoPage?id=' + this.elevatorDetail.id; 
			uni.navigateTo({
				url: urls,
			});
		},
	},
};
</script>

<style>
page {
  background: #f3f6f8;
}
</style>
<style lang="scss" scoped>
// 项目地址卡片
.addressBox {
  width: 710rpx;
  margin: 0 auto;
  background: #fff;
  border-radius: 8rpx;
  font-size: 24rpx;
  padding: 20rpx 22rpx 16rpx 16rpx;
  font-size: 24rpx;
  color: #999;
  box-sizing: border-box;
  margin-bottom: 20rpx;
  position: relative;
  z-index: 9;
  display: flex;

  .top {
    display: flex;

    .name {
      display: flex;
      // padding-left: 14rpx;
      font-weight: 600;
      color: #333;
      align-items: center;
    }

    image {
      width: 32rpx;
      height: 32rpx;
    }
  }

  .buildAddressBox {
    display: flex;
  }

  .buildAddress {
    padding: 6rpx 20rpx 0 32rpx;
    margin-left: 10rpx;
    width: 388rpx;
    margin-right: 30rpx;
    .buildings {
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      max-width: 388rpx;
      font-size: 20rpx;
      color: #666;
    }
  }

  .addressBox_right {
    display: flex;
    flex: 1;
    justify-content: flex-end;

    align-items: center;
  }

  .gpsAndCall {
    position: relative;
    display: flex;
    align-items: center;
    width: 190rpx;

    .gpsAndCall_item {
      display: flex;
      flex: 1;
      color: #666;
    }

    .guide {
      justify-content: flex-end;
    }

    image {
      width: 32rpx;
      height: 32rpx;
    }

    .line {
      width: 2rpx;
      height: 24rpx;
      background: #e9e9e9;
      position: absolute;
      left: 50%;
      top: 6rpx;
    }
  }
}

.taskStep {
  .header {
    background: #f3f6f8;
    // height: 366rpx;
    position: sticky;
    top: 0;
    z-index: 300;
    .nav {
      // position: sticky;
      // top: 0;
      // z-index: 112;
    }

    .bg {
      width: 376rpx;
      height: 366rpx;
      position: absolute;
      top: 0;
      right: 0;
    }

    .header_item {
      padding: 28rpx 40rpx;
      // height: 400rpx;
      // background: #f3f6f8;
    }

    .header_top {
      display: flex;
      // justify-content: space-between;
      align-items: center;
      margin-bottom: 4rpx;
      // position: relative;
      // z-index: 300;

      .header_top_left {
        font-size: 38rpx;
        color: #333;
        font-weight: 600;
      }

      .flex {
        text {
          display: inline-block;
          width: 16rpx;
          height: 16rpx;
          border-top: 2rpx #1b181b solid;
          border-right: 2rpx #1b181b solid;
          transform: rotate(45deg);
        }
      }
    }

    .header_bottom {
      // position: relative;
      // z-index: 10;
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-top: 8rpx;
      .header_bottom_left {
        font-size: 24rpx;
        color: #999;

        display: flex;
      }
      .header_bottom_right {
        display: flex;
        padding-left: 10px;
        z-index: 100;
        justify-content: flex-end;
        image {
          width: 32rpx;
          height: 32rpx;
          display: flex;
        }
      }
    }
  }

  .content {
    padding: 0 20rpx;
    background-color: #f3f6f8;

    .content_chi {
      border-radius: 8rpx;
      background: #ffffff;

      .t_name {
        padding: 30rpx;
        font-size: 32rpx;
        font-weight: 500;
        color: #333333;
      }

      .t_Times {
        margin-bottom: 30rpx;
        margin-left: 30rpx;
        font-size: 28rpx;
        color: #666666;

        image {
          width: 28rpx;
          height: 28rpx;
          vertical-align: middle;
          margin-right: 5rpx;
        }

        text:nth-of-type(2) {
          background: #ffefe3;
          font-size: 24rpx;
          color: #fa6400;
          padding: 5rpx 10rpx 5rpx 10rpx;
          margin-left: 10rpx;
        }
      }
    }
  }
}
</style>
